package controller

import (
	"errors"
	"fmt"
	"net/http"
	"server_cluster/common/logger"
	"server_cluster/http/model"
	"server_cluster/http/service"

	"github.com/gin-gonic/gin"
)

func (c *Controller) login(ctx *gin.Context) {
	req := new(model.GmAccountLoginReq)
	err := ctx.ShouldBindJSON(req)
	if err != nil {
		logger.Error("parse json error: %v", err)
		ctx.JSON(http.StatusOK, ParamError)
		return
	}
	uid, token, err := c.s.Login(req.Username, req.Password)
	if err != nil {
		switch {
		case errors.Is(err, service.GmAccountNotExist):
			fmt.Println("account not exist")
			ctx.JSON(http.StatusOK, GmUsernameOrPasswordError)
			return
		case errors.Is(err, service.GmPasswordError):
			fmt.Println("password error")
			ctx.JSON(http.StatusOK, GmUsernameOrPasswordError)
			return
		default:
			logger.Error("account login error: %v", err)
			ctx.JSON(http.StatusOK, UnknownError)
			return
		}
	}
	ctx.JSON(http.StatusOK, &model.CommonRsp{Code: 20000, Data: &model.GmAccountLoginRsp{Uid: uid, Token: token}})
}
